package com.ysxsoft.wdg.ui.activity.center_zy;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Parcelable;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.socks.library.KLog;
import com.umeng.socialize.UMShareAPI;
import com.youth.banner.Banner;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.DiscussBean;
import com.ysxsoft.wdg.bean.DiscussBean2;
import com.ysxsoft.wdg.bean.zy.GoodsBean;
import com.ysxsoft.wdg.bean.zy.GoodsRulesBean;
import com.ysxsoft.wdg.bean.zy.ZyGoodsBean;
import com.ysxsoft.wdg.constant.MCConfig;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.login.LoginValid;
import com.ysxsoft.wdg.ui.activity.shopcart.ShopcartActivity;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.ViewUtils;
import com.ysxsoft.wdg.util.WebViewUtils;
import com.ysxsoft.wdg.util.banner.BannerImageLoader;
import com.ysxsoft.wdg.util.delayaction.Action;
import com.ysxsoft.wdg.util.delayaction.SingleCall;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.SharePopupWindow;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class GoodsDetailActivity extends BaseActivity {

    private String mobile;

    public static void start(Context context, String goodsid) {
        Intent intent = new Intent(context, GoodsDetailActivity.class);
        intent.putExtra("goodsid", goodsid);
        context.startActivity(intent);
    }

    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_old_money)
    TextView tvOldMoney;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_yun)
    TextView tvYun;
    @BindView(R.id.tv_sold)
    TextView tvSold;
    @BindView(R.id.iv_pl_tx)
    ImageView ivPlTx;
    @BindView(R.id.tv_pl_nick)
    TextView tvPlNick;
    @BindView(R.id.tv_pl_content)
    TextView tvPlContent;
    @BindView(R.id.ll_pl_1)
    LinearLayout llPl1;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.iv_photos)
    BGANinePhotoLayout ninePhotoLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private int bannerHeight = 710;
    private String uid = "", goodsid = "";
    private UMShareAPI mShareAPI;
    private SharePopupWindow popupWindow;
    private String imageUrl = "";

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());

        ViewUtils.setDeletLine(tvOldMoney);
        WebViewUtils.init(webView);
        webView.setWebViewClient(new WebViewClient());

        uid = SharePrefUtils.getUserId();
        goodsid = getIntent().getStringExtra("goodsid");
        mShareAPI = UMShareAPI.get(this);
        popupWindow = new SharePopupWindow(this, mShareAPI);

        multStatusView.showLoading();
        mApiHelper.getZyGoodsdetail(uid, goodsid, new Observer<BaseBean<ZyGoodsBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<ZyGoodsBean> baseBean) {

                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    mobile = baseBean.getData().getMobile();

                    GoodsBean goodsBean = baseBean.getData().getGoods();
                    tvMoney.setText(getString(R.string.price_rmb, goodsBean.getL_price()));
                    tvOldMoney.setText(getString(R.string.price_rmb, goodsBean.getPrice()));

                    tvName.setText(goodsBean.getName());
                    tvYun.setText(goodsBean.getYun().equals("0.00") ? "免运费" : "运费" + goodsBean.getYun());
                    tvSold.setText("月销" + goodsBean.getSold() + "笔");

                    tvCollect.setSelected(goodsBean.getSou() == 1);

                    banner.setImages(goodsBean.getPictures());
                    banner.start();
                    WebViewUtils.setH5Data(webView, goodsBean.getDetail());

                    List<DiscussBean2> discussList = baseBean.getData().getDiscuss();
                    if (discussList.size() == 0) {
                        llPl1.setVisibility(View.GONE);
                    } else {
                        llPl1.setVisibility(View.VISIBLE);
                        DiscussBean2 discussBean = discussList.get(0);
                        ViewUtils.loadCircleImage(mContext, discussBean.getAvatar(), ivPlTx);
                        tvPlNick.setText(discussBean.getNickname());
                        tvPlContent.setText(discussBean.getContent());
                    }

                    List<DiscussBean2> dis = baseBean.getData().getDiscuss();
                    if (dis != null && dis.size() > 0) {
                        DiscussBean2 d = dis.get(0);
                        ninePhotoLayout.setData((ArrayList<String>) d.getPic());
                        ninePhotoLayout.setDelegate(new BGANinePhotoLayout.Delegate() {
                            @Override
                            public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                File downloadDir = new File(MCConfig.PICTURE_DIR);
                                BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder = new BGAPhotoPreviewActivity.IntentBuilder(mContext)
                                        .saveImgDir(downloadDir); // 保存图片的目录，如果传 null，则没有保存图片功能
                                photoPreviewIntentBuilder
                                        .previewPhotos((ArrayList<String>) models).currentPosition(position); // 当前预览图片的索引
                                mContext.startActivity(photoPreviewIntentBuilder.build());
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
                multStatusView.showContent();
            }
        });

    }

    @Override
    protected void setListener() {

        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int x, int y, int oldScrollX, int oldScrollY) {
                KLog.e("y=" + y + ",oldScrollY=" + oldScrollY);
                if (y <= 0) {
                    title.setBackgroundColor(Color.parseColor("#00000000"));
                } else if (y > 0 && y <= bannerHeight) {
                    float scale = (float) y / bannerHeight;
                    float alpha = (255 * scale);
                    // 只是layout背景透明
                    title.setBackgroundColor(Color.argb((int) alpha, 254, 74, 112));
                } else {
                    title.setBackgroundColor(Color.parseColor("#fe4a70"));
                }
            }
        });


    }


    private String code = "buy";

    @OnClick({R.id.tv_phone, R.id.tv_collect, R.id.tv_add_cart,
            R.id.tv_buy, R.id.ll_2_pl, R.id.btn_finish,
            R.id.btn_share, R.id.btn_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.tv_phone:
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showToast("请稍后再试");
                    return;
                }
                AlertViewFactory.getInstance().getCallAlert(this, mobile).show();
                break;
            case R.id.tv_collect:
                mApiHelper.colZyGoods(goodsid, uid, new Observer<BaseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseBean baseBean) {
                        ToastUtils.showToast(baseBean.getMs());
                        if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                            tvCollect.setSelected(!tvCollect.isSelected());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showToast("请稍后再试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
                break;
            case R.id.tv_add_cart:
                code = "cart";
                SingleCall.getInstance().addAction(new Action() {
                    @Override
                    public void call() {
                        getRules();
                    }
                }).addValid(new LoginValid(mContext, 1)).doCall();
                break;
            case R.id.tv_buy:
                code = "buy";
                SingleCall.getInstance().addAction(new Action() {
                    @Override
                    public void call() {
                        getRules();
                    }
                }).addValid(new LoginValid(mContext, 1)).doCall();
                break;
            case R.id.ll_2_pl:
                GoodsPlActivity.start(mContext, goodsid);
                break;
            case R.id.btn_share://分享
                popupWindow.setShareData(getString(R.string.app_name), "商品详情"/*+data*/, UrlHost.BASE_URL+"/index.html#/details?store=1&id="+goodsid, "", 0);
                popupWindow.show(mRootView);
                break;
            case R.id.btn_cart:
                ShopcartActivity.start(GoodsDetailActivity.this);
                break;
        }
    }

    private void getRules() {
        mApiHelper.getZyRules(goodsid, new Observer<BaseBean<GoodsRulesBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<GoodsRulesBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    GoodsBean product = baseBean.getData().getProduct();

                    Intent intent = new Intent(mContext, GoodsRulesActivity.class);
                    intent.putExtra("goodsBean", product);
                    intent.putExtra(GoodsRulesActivity.JUMP_CODE, code);
                    intent.putParcelableArrayListExtra("rules", (ArrayList<? extends Parcelable>) baseBean.getData().getRule());
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_bottom, 0);
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }


}
